package com.gensdai.leliang.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.activity.ActivityBrand;
import com.gensdai.leliang.adapter.BrandListRecyclerAdapter;
import com.gensdai.leliang.base.BaseFragment;
import com.gensdai.leliang.common.adapter.BrandListAdapterRec;
import com.gensdai.leliang.common.adapter.BrandTitleAdapterRec;
import com.gensdai.leliang.common.adapter.ContentTitleAdapterRec;
import com.gensdai.leliang.common.adapter.MainMenuAdapterRec;
import com.gensdai.leliang.common.bean.BrandListBean;
import com.gensdai.leliang.common.bean.TitleBean;
import com.gensdai.leliang.common.bean.WechatBean;
import com.gensdai.leliang.entity.HomeBean;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.entity.parseBean.BaseParseList;
import com.gensdai.leliang.recyclerViewUtils.HorizontalDividerItemDecoration;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserverList;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/6/2.
 */

public class BrandFragment extends BaseFragment {


    @BindView(R.id.brandList)
    RecyclerView brandList;
    Unbinder unbinder;

    LinearLayoutManager layoutManager;

    DelegateAdapter delegateAdapter;
    List<DelegateAdapter.Adapter> adapters;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_brand_list, null);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        brandList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.dividerColor)).size(16).build());
//        brandList.setHasFixedSize(true);
//        layoutManager = new LinearLayoutManager(getActivity());
//        layoutManager.setOrientation(OrientationHelper.VERTICAL);
//        brandList.setLayoutManager(layoutManager);
//
//        BrandListRecyclerAdapter adapter = new BrandListRecyclerAdapter(getActivity());
//        brandList.setAdapter(adapter);

        initRecyclerView();
        getBrandList();

    }

    private void initRecyclerView() {
        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());
        brandList.setLayoutManager(layoutManager);
        // layoutManager.setReverseLayout(true);

        RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = ((VirtualLayoutManager.LayoutParams) view.getLayoutParams()).getViewPosition();
                outRect.set(4, 4, 4, 4);
            }
        };

        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        brandList.setRecycledViewPool(viewPool);

        // recyclerView.addItemDecoration(itemDecoration);
        viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        brandList.setAdapter(delegateAdapter);

        adapters = new LinkedList<>();
    }


    public void getBrandList() {
        Map<String, String> params = new HashMap<>();
        params.put("clientType", AppApplication.ClientType);
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().getBrandList(params))
                .compose(this.<BaseParseList<BrandListBean>>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new BaseObserverList<BrandListBean>(getActivity()) {
                    @Override
                    public void onHandleSuccess(List<BrandListBean> t) {
                        attachView(t);
                    }

                    @Override
                    public void onHandleError(int code, String message) {

                    }
                });
    }


    private void attachView(List<BrandListBean> t) {
        if (t != null && t.size() > 0) {
            for (int i = 0; i < t.size(); i++) {
                inittitle(t.get(i).BrandParentName, i);
                initBrandList(t.get(i).brandProductList);
            }
        }

        //初始化完毕后开始适配
        delegateAdapter.setAdapters(adapters);
    }

    //添加首页的子标题
    private void inittitle(String title, int position) {
        if (adapters != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            layoutHelper.setPadding(getResources().getDimensionPixelOffset(R.dimen.px20dp), 0, 0, 0);
            if (position != 0) {
                layoutHelper.setMargin(0, getResources().getDimensionPixelOffset(R.dimen.px20dp), 0, 0);
            } else {

                layoutHelper.setMargin(0, 0, 0, 0);
            }
            layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
            BrandTitleAdapterRec bannerAdapter = new BrandTitleAdapterRec(getActivity(), layoutHelper, title);
            adapters.add(bannerAdapter);
        }
    }

    private void initBrandList(List<HomeBean.BrandBean> beans) {

        GridLayoutHelper layoutHelper = new GridLayoutHelper(3);
        layoutHelper.setMargin(0, 0, 0, 0);
        layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
        layoutHelper.setAutoExpand(false);
        layoutHelper.setPadding(0, getResources().getDimensionPixelOffset(R.dimen.px24dp), 0, getResources().getDimensionPixelOffset(R.dimen.px24dp));
        //横间距
        layoutHelper.setHGap(0);
        //垂直间距
        layoutHelper.setVGap(getResources().getDimensionPixelOffset(R.dimen.px20dp));
        if (adapters != null) {
            BrandListAdapterRec menuAdapter = new BrandListAdapterRec(getActivity(), layoutHelper, beans);
            menuAdapter.setOnMenuTypeClick(new BrandListAdapterRec.MenuTypeOnclickListener<HomeBean.BrandBean>() {
                @Override
                public void OnPositionClick(HomeBean.BrandBean menu, int position) {
                    Intent it = new Intent(getActivity(), ActivityBrand.class);
                    it.putExtra(ActivityBrand.EXTRA_BRAND_ID, menu);
                    startActivity(it);
                }
            });
            adapters.add(menuAdapter);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
